<?php


namespace app\admin\service\business\controllers\City;


use app\admin\service\business\BaseControllerService;
use app\admin\service\business\controllers\City\Models\CityModel;

/**
 * Class CityService
 *
 * @property-read CityModel $model
 *
 * @package app\admin\service\business\controllers\City
 */
class CityService extends BaseControllerService
{
    protected $rely = [
        'model' => CityModel::class,
    ];

    // 地区类型
    public $type = [
        0 => ['name' => '省', 'value' => 0],
        1 => ['name' => '市', 'value' => 1],
        2 => ['name' => '区', 'value' => 2],
    ];

    /**
     * 查询列表
     *
     * @param array $where
     * @param int $limit
     * @return mixed
     */
    public function resList(array $where, int $limit)
    {
        list($province, $city) = [[], []];

        $list = $this->model->getList($where['key'] ?? [], [], true, $limit)->map(function ($v) use (&$province, &$city) {
            if ($v['pid']['province_id']) array_push($province, $v['pid']['province_id']);
            if ($v['pid']['city_id']) array_push($city, $v['pid']['city_id']);

            if (!$v['pid']['province_id'] && !$v['pid']['city_id']) $type = 0;
            if ($v['pid']['province_id'] && $v['pid']['city_id']) $type = 2;
            if ($v['pid']['province_id'] && !$v['pid']['city_id']) $type = 1;

            $v->typeName = $this->type[$type]['name'];

            return $v;
        });

        // 获取省列表、市列表
        list($province, $city) = [
            arrConversion($this->model->getFormIdsCityList($province)->toArray(), 'id'),
            arrConversion($this->model->getFormIdsCityList($city)->toArray(), 'id')
        ];

        // 处理地址省市
        $list->map(function ($v) use ($province, $city) {
            $v->pid = [
                'province' => $v->pid['province_id'] ? $province[$v->pid['province_id']]['name'] : '无',
                'city' => $v->pid['city_id'] ? $city[$v->pid['city_id']]['name'] : '无',
            ];

            return $v;
        });

        return $list;
    }
}